<template>
    <el-cascader ref="selfCascaderSelect" :placeholder="placeholder" :collapse-tags="collapseTags" :value="value"
        :show-all-levels="showAllLevels" :options="cascaderOptions" :props="cascaderProps" :clearable="clearable"
        :filterable="filterable" @change="selectIds" :class="[full ? 'full-box-class' : '']" />
</template>

<script>
// 适用与后端需要所有选中（包含半选中）的id数组，且回显数据时的id数组与设置的id数组一致
export default {
    name: 'cascader-select',
    props: {
        // 提示语
        placeholder: {
            type: String,
            default: '请选择',
        },
        collapseTags: {
            type: Boolean,
            default: false,
        },
        cascaderOptions: {
            type: Array,
            default: () => [],
        },
        cascaderProps: {
            type: Object,
            default: () => ({
                value: 'value',
                label: 'label',
                children: 'children',
                multiple: true, //多选
                checkStrictly: false, // 父子是否关联 false为关联 true为不关联
                expandTrigger: 'click',
                // true为返回由该节点所在的各级菜单的值所组成的数组 false只返回该节点的值
                emitPath: false,
            }),
        },
        clearable: {
            type: Boolean,
            default: true,
        },
        // 是否显示所有选项的完整路径
        showAllLevels: {
            type: Boolean,
            default: true,
        },
        // 是否可搜索
        filterable: {
            type: Boolean,
            default: false,
        },
        // 选中的id数组
        value: {
            type: Array,
            default: () => [],
        },
        full: {
            type: Boolean,
            default: false,
        },
    },
    methods: {
        // 返回选中的id（包含半选中的父节点）数组
        selectIds() {
            let checkedNodesArr = this.$refs.selfCascaderSelect.getCheckedNodes()
            let checkedIds = []
            checkedNodesArr.forEach(item => {
                let idsArr = this.getCheckIds(item)
                if (idsArr.length) {
                    idsArr.forEach(id => {
                        if (!checkedIds.includes(id)) {
                            checkedIds.push(id)
                        }
                    })
                }
            })
            this.$emit('input', checkedIds)
        },
        // 递归获取node及其父级的id
        getCheckIds(node, checkedIds = []) {
            checkedIds.push(node.value)
            if (node.parent) this.getCheckIds(node.parent, checkedIds)
            return checkedIds
        },
    },
}
</script>

<style scoped lang="scss">
.full-box-class {
    width: 100%;
}
</style>